package com.yxy.ms.manager.web;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yxy.ms.manager.common.Common;
import com.yxy.ms.manager.common.Results;
import com.yxy.ms.manager.entity.po.ClearErrorInfo;
import com.yxy.ms.manager.entity.po.ClearMessageValidateRecord;
import com.yxy.ms.manager.entity.po.ClearPendingCharge;
import com.yxy.ms.manager.entity.po.ClearSendRecord;
import com.yxy.ms.manager.service.ClearDataTempService;
import com.yxy.ms.manager.service.MonitorService;

@RestController
@RequestMapping(value = "/clear/")
public class ClearController {
    @Autowired
    ClearDataTempService clearDataTempService;
    @Autowired
    MonitorService monitorService;

    /**
     * <函数描述>清分发送记录表列表
     * 
     * @return
     */
    @RequestMapping(value = "getClearMessageValidateRecords", method = RequestMethod.POST)
    public Results getClearMessageValidateRecords(@RequestBody String data) {
        Page<ClearMessageValidateRecord> list = monitorService.getClearMessageValidateRecords(conditional(data));
        return Common.results200(getPageData(list));
    }

    /**
     * <函数描述>清分发送记录表列表
     * 
     * @return
     */
    @RequestMapping(value = "getClearSendRecords", method = RequestMethod.POST)
    public Results getClearSendRecords(@RequestBody String data) {
        Page<ClearSendRecord> list = monitorService.findClearSendRecords(conditional(data));
        return Common.results200(getPageData(list));
    }

    /**
     * <函数描述>清分待记账列表
     * 
     * @return
     */
    @RequestMapping(value = "getClearPendingCharges", method = RequestMethod.POST)
    public Results getClearPendingCharges(@RequestBody String data) {
        Page<ClearPendingCharge> list = monitorService.getClearPendingCharges(conditional(data));
        return Common.results200(getPageData(list));
    }

    /**
     * <函数描述>清分临时表发行方下拉列表
     * 
     * @return
     */
    @RequestMapping(value = "loadp01IssureId", method = RequestMethod.GET)
    public Results loadp01IssureId() {
        return Common.results200(clearDataTempService.loadp01IssureId());
    }

    /**
     * <函数描述>下载文件
     * 
     * @param request
     *            请求
     * @param response
     *            响应
     * @return
     */
    @RequestMapping(value = "downLoadClearErrorFile", method = RequestMethod.GET)
    public Results downLoadFile(HttpServletRequest request, HttpServletResponse response) {
        String queryString = request.getQueryString();
        if (StringUtils.isBlank(queryString)) {
            return Common.results400("下载出错，无参数");
        }

        String query = new String(Base64.getUrlDecoder().decode(queryString));
        String[] params = new String[2];

        Pattern pattern = Pattern.compile("id=([^&]*)");
        Matcher matcher = pattern.matcher(query);
        if (matcher.find()) {
            params[0] = StringUtils.replaceAll(matcher.group(), "^id=", "");
        }

        pattern = Pattern.compile("type=(\\w)*$");
        matcher = pattern.matcher(query);
        if (matcher.find()) {
            params[1] = StringUtils.replaceAll(matcher.group(), "^type=", "");
        }

        pattern = Pattern.compile("dateTime=(\\w)*$");
        matcher = pattern.matcher(query);
        if (matcher.find()) {
            params[2] = StringUtils.replaceAll(matcher.group(), "^dateTime=", "");
        }

        ClearErrorInfo clearErrorInfo = monitorService.getClearErrorInfo(params[0], Integer.parseInt(params[1]), null);
        if (clearErrorInfo == null) {
            return Common.results400("下载出错，下载数据不存在");
        }

        if (StringUtils.isBlank(clearErrorInfo.getErrorFileName())) {
            clearErrorInfo.setErrorFileName(params[0] + ".json");
        }

        OutputStream os = null;
        try {
            String content = clearErrorInfo.getErrorInfo();
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode(clearErrorInfo.getErrorFileName(), "UTF-8"));
            os = response.getOutputStream();
            IOUtils.copy(IOUtils.toInputStream(content, "UTF-8"), os);

        } catch (IOException e) {
            return Common.results400("下载出错," + e);
        } finally {
            IOUtils.closeQuietly(os);
        }

        return null;

    }

    @SuppressWarnings("unchecked")
    protected <T> T conditional(String data, Class<?> classType) {
        JSONObject root = JSON.parseObject(data);
        JSONObject params = root.getJSONObject("params");
        return (params != null ? (T)params.toJavaObject(classType) : null);
    }

    protected JSONObject conditional(String data) {
        JSONObject root = JSON.parseObject(data);
        JSONObject page = root.getJSONObject("page");
        JSONObject params = root.getJSONObject("params");

        if (page != null) {
            PageHelper.startPage(null != page.getInteger("pageIndex") ? page.getInteger("pageIndex") : 1,
                null != page.getInteger("pageSize") ? page.getInteger("pageSize") : 10);
            PageHelper.orderBy(StringUtils.isEmpty(page.getString("orderBy")) ? "" : page.getString("orderBy"));
        }

        return params;
    }

    protected Map<String, Object> getPageData(Page<?> page) {
        Map<String, Object> result = new HashMap<String, Object>();
        // 总记录数
        result.put("total", page.getTotal());
        // 总页数
        result.put("pages", page.getPages());
        // 每页记录数
        result.put("pageSize", page.getPageSize());
        // 当前页码
        result.put("pageNum", page.getPageNum());
        // 结果
        result.put("rows", page.getResult());
        return result;
    }

}
